package routers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//FolwCreate 路由：流程创建
func FolwCreate(c echo.Context) error {
	wfidStr := c.Param("wfid")
	wfid, err := strconv.Atoi(wfidStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "wfid不能为空，且必须为Int！")
	}
	userIDStr := c.FormValue("userID")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "userID不能为空，且必须为Int！")
	}
	runID, err := workflow.Create(wfid, userID, nil)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.String(http.StatusOK, fmt.Sprintf(`{"runID":%d}`, runID))
}

//FolwSubmit 路由：流程提交
func FolwSubmit(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	userIDStr := c.FormValue("userID")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "userID不能为空，且必须为Int！")
	}
	desc := c.FormValue("desc")
	bType := c.FormValue("bType")
	var subType string
	if bType == "agree" {
		subType = "1"
	} else {
		subType = "4"
	}
	if err := workflow.Submit(runID, userID, desc, subType); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}

//FolwSubmitBatch 路由：流程提交
// func FolwSubmitBatch(c echo.Context) error {
// 	runIDStr := c.FormValue("runIDs")
// 	var runIDs []int
// 	err := json.Unmarshal([]byte(runIDStr), &runIDs)
// 	if err != nil {
// 		return echo.NewHTTPError(http.StatusBadRequest, "runIDs必须是int类型的数组！")
// 	}
// 	userIDStr := c.FormValue("userID")
// 	userID, err := strconv.Atoi(userIDStr)
// 	if err != nil {
// 		return echo.NewHTTPError(http.StatusBadRequest, "userID必须是int类型！")
// 	}
// 	desc := c.FormValue("desc")
// 	bType := c.FormValue("bType")
// 	var subType string
// 	if bType == "agree" {
// 		subType = "1"
// 	} else {
// 		subType = "4"
// 	}
// 	tx := base.DB.Begin()
// 	for _, runID := range runIDs {
// 		if err = workflow.SubmitWithTX(runID, userID, desc, subType, tx); err != nil {
// 			tx.Rollback()
// 			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
// 		}
// 	}
// 	tx.Commit()
// 	return c.JSON(http.StatusOK, "ok")
// }
func FolwSubmitBatch(c echo.Context) error {
	runIDStr := c.FormValue("runIDs")
	var runIDs []int
	err := json.Unmarshal([]byte(runIDStr), &runIDs)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runIDs必须是int类型的数组！")
	}
	userIDStr := c.FormValue("userID")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "userID必须是int类型！")
	}
	desc := c.FormValue("desc")
	bType := c.FormValue("bType")
	ishldstr := c.FormValue("ishld")
	ishld, err := strconv.Atoi(ishldstr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "userID必须是int类型！")
	}
	var subType string
	if bType == "agree" {
		subType = "1"
	} else {
		subType = "4"
	}

	tx := base.DB.Begin()
	for _, runID := range runIDs {
		if err = workflow.SubmitWithTX(runID, userID, desc, subType, tx, ishld); err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "ok")
}

//FolwAbort 路由：流程中止
func FolwAbort(c echo.Context) error {
	runIDStr := c.FormValue("runIDs")
	var runIDs []int
	err := json.Unmarshal([]byte(runIDStr), &runIDs)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runIDs必须是int类型的数组！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	tx := base.DB.Begin()
	for _, runID := range runIDs {
		if err := workflow.AbortWithTx(runID, claims.UserID, tx); err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, "ok")
}

//FolwAbort 路由：流程中止
func FolwDelete(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	if err := workflow.Delete(runID); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}

//FolwSendBack 路由：流程退回
func FolwSendBack(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	userIDStr := c.FormValue("userID")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "userID不能为空，且必须为Int！")
	}
	backStepIDStr := c.FormValue("backStepID")
	backStepID, err := strconv.Atoi(backStepIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "backStepID不能为空，且必须为Int！")
	}
	desc := c.FormValue("desc")
	if err := workflow.SendBack(runID, userID, backStepID, desc); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}

//GetFolwExecutor 路由：获取流程执行人
func GetFolwExecutor(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	userIDs, _, err := workflow.GetExecutor(runID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	userMap := make(map[int]string, len(userIDs))
	cache := base.GetEmployeeCache()
	for _, uid := range userIDs {
		userName, err := cache.GetNameByID(uid)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		orgName, err := cache.GetDeptNameByID(uid)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		userMap[uid] = fmt.Sprintf("%s(%s)", userName, orgName)
	}
	return c.JSON(http.StatusOK, userMap)
}

//GetFolwRunInfo 路由：获取流程运行
func GetFolwRunInfo(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	runInfo, err := workflow.GetRunInfo(runID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, runInfo)
}

//GetFolwRunInfoBak 路由：获取流程运行 	 查看2021年7月之前的数据
func GetFolwRunInfoBak(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	runInfo, err := workflow.GetRunInfoBak(runID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, runInfo)
}

//SetFolwExecutor 路由：设置流程执行人
func SetFolwExecutor(c echo.Context) error {
	runIDStr := c.Param("runID")
	runID, err := strconv.Atoi(runIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	stepIDStr := c.FormValue("stepID")
	stepID, err := strconv.Atoi(stepIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "stepID不能为空，且必须为Int！")
	}
	userIDarr := strings.Split(c.FormValue("userIDstr"), ",")
	userIDs := make([]int, len(userIDarr), len(userIDarr))
	for i, uidStr := range userIDarr {
		uid, err := strconv.Atoi(uidStr)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "userIDstr不能为空，多个值逗号隔开，且必须为Int！")
		}
		userIDs[i] = uid
	}
	if err := workflow.SetExecutor(runID, stepID, userIDs); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}
func WorkFlowCompRouter(c echo.Context) error {
	workflow := base.WFContext.GetWorkFlow("compworkflow")
	return c.JSON(http.StatusOK, workflow.Actions)
}
func WorkFlowIndiRouter(c echo.Context) error {
	workflow := base.WFContext.GetWorkFlow("indiworkflow")
	return c.JSON(http.StatusOK, workflow.Actions)
}

func IsManagerRouter(c echo.Context) error {
	permIDStr := c.Param("permID")
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "permID不能为空，且必须为Int！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	return c.JSON(http.StatusOK, workflow.IsManager(permID, claims.UserID))
}

//GetCompIsDiviRouter 查询对公是否认定
func GetCompIsDiviRouter(c echo.Context) error {
	cunm := c.FormValue("cunm")
	divi := c.FormValue("divi")
	tx := base.DB.Begin()
	var isdivi string
	rows, err := tx.Raw("SELECT dbo.GetCompIsDivi(?,?)", cunm, divi).Rows()
	for rows.Next() {
		rows.Scan(&isdivi)
	}
	if err != nil {
		tx.Rollback()
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tx.Commit()
	return c.JSON(http.StatusOK, isdivi)
}

//GetIndiIsDiviRouter 查询零售是否认定
func GetIndiIsDiviRouter(c echo.Context) error {
	zjhm := c.FormValue("zjhm")
	tx := base.DB.Begin()
	var count int
	var isdivi string
	row := tx.Raw("SELECT COUNT(*) FROM V_INDI_CLIE_FLOW WHERE IDNO=? AND ISXJK=1", zjhm).Row()
	row.Scan(&count)
	if count > 0 {
		rows, err := tx.Raw("SELECT [dbo].[GetIndiIsDivi](?)", zjhm).Rows()
		for rows.Next() {
			rows.Scan(&isdivi)
		}
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	} else {
		isdivi = "W"
	}
	tx.Commit()
	return c.JSON(http.StatusOK, isdivi)
}
